
//app.js
var QQMapWX = require('./utils/qqmap-wx-jssdk.js');
var Promise = require('./utils/bluebird.min.js')
import { Config } from './utils/config.js';


App({
  onLaunch: function () {
  },
  onShow:function(){
  },
  globalData: {
    userInfo: null,
    showLogin:false,
  },
  //微信登录
  login: function (cb) {
    var that = this;
    var session_key = wx.getStorageSync('session_key');
    //过期时间
    var date_expiration = wx.getStorageSync('date_expiration');
    var now_time = Date.parse(new Date());
    if (session_key == '' || date_expiration < now_time){
      //获取授权
      wx.getSetting({
        success: function (result) {
          if (result.authSetting['scope.userInfo']) {
            wx.login({
              // 发送 res.code 到后台换取 openId, sessionKey, unionId
              success: function (res) {
                var code = res.code;  //获取code
                wx.getUserInfo({  //得到rawData, signatrue, encryptData
                  success: function (data) {
                    that.Baselogin(code,data);
                  },
                  fail: function () {
                    that.globalData.showLogin = true;
                    typeof cb == "function" && cb(that.globalData.showLogin)
                  }
                })
              },
              fail: function () {
                wx.showToast({
                  title: "授权登录失败",
                  icon: 'none',
                  duration: 2000
                })
              }

            })  
          } else {
            that.globalData.showLogin = true;
            typeof cb == "function" && cb(that.globalData.showLogin)
          }

        }
      })
    }
  
  },

  Baselogin: function (code,data){
   var that = this;

   var code =code;  //获取code
   var userinfo = data.userInfo;
   var rawData = data.rawData;
   var signature = data.signature;
   var encryptedData = data.encryptedData;
   var iv = data.iv;
   wx.request({
     url: Config.restUrl + 'Api/Agent/getOpenid',
     data: {
       "code": code,
       "rawData": rawData,
       "signature": signature,
       'iv': iv,
       'encryptedData': encryptedData,
       'nickname': userinfo.nickName,
       'avatarUrl': userinfo.avatarUrl,
     },
     method: 'GET',
     success: function (res) {
       var res = res.data;
       if (res.status == 1) {
         var timestamp = Date.parse(new Date());
         var expiration = timestamp + 86400000;
         wx.setStorageSync('date_expiration', expiration);
         wx.setStorageSync('session_key', res.session_key);
         wx.setStorageSync('user', res.user);
         that.globalData.showLogin = false;
         that.globalData.userInfo = userinfo;
       } else {
         wx.showToast({
           title: res.info,
           icon: 'none',
           duration: 2000
         })
       }

     }
   })
  },

 location: function (){
    var that = this
    // 实例化腾讯地图API核心类
    var qqmapsdk = new QQMapWX({
      key: 'VHRBZ-G3JW4-E5FUC-XUAUQ-LF5SZ-4ZBIV' // 必填
    });

    return new Promise(function (resolve, reject) {
      //1、获取当前位置坐标
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          //2、根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: res.latitude,
              longitude: res.longitude
            },
            success: function (addressRes) {
              var address = addressRes.result.address_component;
              //查看地址是否开通
              wx.request({
                url: 'https://zhaodeng2.ystsj.net/index.php/Api/Index/getAddress',
                data: {
                  "district": address.district,
                },
                method: 'GET',
                success: function (res) {
                  var data = res.data;
                  data.district = address.district;
                  resolve(data); 
                },
                fail: function () {
                  reject('error');
                }
              })
            }

          })
        }
      })
    })

    
  },
  studentCheckIn:function(){
    wx.getSetting({
      success: function (res) {
        console.log(res)
        return false;
        if (res.authSetting["scope.userLocation"] == true) {
          console.log("用户已开启定位授权");
        } else {
          wx.showModal({
            title: '位置信息授权',
            content: '位置授权暂未开启，无法完成签到',
            confirmText: '开启授权',
            confirmColor: '#345391',
            cancelText: '仍然拒绝',
            cancelColor: '#999999',
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  fail: function () {
                    console.log('openSetting.failed')
                  }
                })
              }
              if (res.cancel) {
                wx.showModal({
                  title: '签到失败',
                  content: '无法使用定位权限，签到失败',
                  confirmText: '太遗憾了',
                  confirmColor: '#345391',
                  showCancel: false
                })
              }
            }
          })
        }
      }
    })  
  }
})